import org.junit.Test;

import java.util.Arrays;
import java.util.Random;

/**
 * @author TaoTaojs
 * @date 2021/4/1 下午4:32
 * <p>Description</p>
 * <h2>功能描述</h2>
 * 红包算法模拟
 * <h3>主要功能：</h3>
 * <ol>
 *     <li>TODO</li>
 * </ol>
 * <h3>关联类</h3>
 * <p>参考链接：</p>
 * <h2>更新日志</h2>
 * [author]        [time]                      [version]          [desc]
 * TaoTaojs        2021/4/1 下午4:32             V1.0
 */

public class ARedEnvelope {

    @Test
    public void test(){
        for (int i = 0; i < 100; i++) {
            test22();
            System.out.println("");
        }
    }

    public void test22(){
        Data data = new Data();
        data.remainMoney = 10.0;
        data.remainSize = 100;
        Double sum = 0.0;
        Double max = 0.0;
        while (data.remainSize > 0){
            double d = test2(data);
            System.out.print(d + ",");
            sum += d;
            if(d > max) {
                max = d;
            }
        }

        System.out.println("");
        System.out.print(sum + "||" + max);

    }

    public double test2(Data data){
        // remainSize 剩余的红包数量
        // remainMoney 剩余的钱
        if (data.remainSize == 1) {
            data.remainSize--;
            double dou = (double) Math.round(data.remainMoney * 100) / 100;
            return (dou);
        }
        Random r     = new Random();
        double min   = 0.01; //
        double max   = data.remainMoney / data.remainSize * 2;
        double money = r.nextDouble() * max;
        money = money <= min ? 0.01: money;
        money = Math.floor(money * 100) / 100;
        data.remainSize--;
        data.remainMoney -= money;
        return (money);
    }

    @Test
    public void test1(){
        Integer money = 10;
        Integer n = 500;
        int fen = (int) (money*100);
        if(fen < n || fen < 1){
            throw new IllegalArgumentException("被拆分的总金额不能小于1分");
        }
        // 创建一个长度等于n的红包数组
        int[] array = new int[n];
        //第一步 每个红包先塞1分
        Arrays.fill(array,1);
        //总金额减去已分配的n 分钱
        fen -= n;
        //第二步，循环遍历如果剩余金额>0 则一直分配
        int i = 0;  //从第一个红包进行分配

        //创建一个随机分配对象
        Random random = new Random();
        while (fen > 0 && i != n){
            int f  = random.nextInt(fen);  //创建范围[0,fen)
            array[random.nextInt(n)] +=  f;
            i++;
            fen -= f;
        }
        //不判断。直接加
        array[random.nextInt(n)] += fen;

        Integer sum = 0;
        Integer max = 0;
        for (int i1 : array) {
            System.out.print(i1/100.0 + "，");
            sum += i1;
            if(i1 > max) {
                max = i1;
            }
        }
        System.out.println("");
        System.out.print(sum + "||" + max);
    }

}

class Data{
    public Double remainMoney;
    public int remainSize;
}
